package com.shitou.shitouproduct.utils;

import com.shitou.shitoucommons.utils.RespBean;
import com.shitou.shitouproduct.entity.CategoryEntity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.ToString;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * class detail:
 *
 * @author 石头人
 */
@SuppressWarnings("all")
public class MenusUtils {

    @Data
    @AllArgsConstructor
    @ToString
    class Menu {
        private int id;
        private int parentId;
        private String name;
        private List<Menu> childrenMenu;
    }

    private List<Menu> menuList = new ArrayList<>();

    public void initList(int level1, int level2, int level3) {
        for (int i = 0; i < level1; i++) {
            // 创建第一层
            Menu menu1 = new Menu(i + 1, 0, "第一层的: " + (i + 1), null);
            menuList.add(menu1);
            for (int i1 = level1; i1 < level1 + level2; i1++) {
                // 创建第二层
                Menu menu2 = new Menu(i1 + 1, menu1.getId(), "第二层的: " + (i1 + 1), null);
                menuList.add(menu2);
                for (int i2 = level2 + level1; i2 < level1 + level2 + level3; i2++) {
                    // 创建第三层
                    Menu menu3 = new Menu(i2 + 1, menu2.getId(), "第三层的: " + (i2 + 1), null);
                    menuList.add(menu3);
                }
            }
        }
    }


    public List<Menu> treeList() {
        initList(5, 5 ,5);
        menuList = menuList.stream().filter(menu -> menu.getParentId() == 0)
                .map(menu -> {
                    menu.setChildrenMenu(getChildrenList(menu, menuList));
                    return menu;
                }).sorted((menu1, menu2)->{
                    return menu1.getId() - menu2.getId();
                }).collect(Collectors.toList());
        return menuList;
    }

    private List<Menu> getChildrenList(Menu parentMenu, List<Menu> menuList) {
        // 传入的不能为空
        if (parentMenu == null || menuList == null) {
            return null;
        }
        // 递归查找
        List<Menu> menus = menuList.stream().filter(menu ->
                menu.getParentId() == parentMenu.getId()
        ).map(menu -> {
            menu.setChildrenMenu(getChildrenList(menu, menuList));
            return menu;
        }).sorted((menu1, menu2)->{
            return menu1.getId() - menu2.getId();
        }).collect(Collectors.toList());

        return menus;
    }

    public void print(List<Menu> menus){
        if ( menus == null ) return;
        for (Menu menu : menus) {
            System.out.println(menu.getName());
            if ( menu.getChildrenMenu() != null ){
                print(menu.getChildrenMenu());
            }
        }
    }


}





